<template>
  <div class="achievement-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>成就管理</span>
          <el-button type="primary" @click="handleAdd">新增成就</el-button>
        </div>
      </template>
      
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="成就名称">
              <el-input v-model="searchForm.name" placeholder="请输入成就名称" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="成就类别">
              <el-select v-model="searchForm.category" placeholder="请选择类别" clearable style="width: 100%">
                <el-option label="签到" value="签到" />
                <el-option label="练习" value="练习" />
                <el-option label="积分" value="积分" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 成就列表 -->
      <el-table :data="achievementList" v-loading="loading" style="width: 100%" border>
        <el-table-column prop="achievementId" label="ID" width="80" />
        <el-table-column prop="name" label="成就名称" min-width="150" />
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column label="图标" width="100">
          <template #default="scope">
            <el-image
              :src="scope.row.iconUrl"
              fit="cover"
              style="width: 40px; height: 40px; border-radius: 50%;"
              lazy
              :preview-src-list="[scope.row.iconUrl]"
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="conditionValue" label="条件值" width="100" />
        <el-table-column prop="pointsReward" label="积分奖励" width="100" />
        <el-table-column prop="isActive" label="是否启用" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>
    
    <!-- 成就编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="currentAchievement" :rules="rules" ref="achievementForm" label-width="120px">
        <el-form-item label="成就名称" prop="name">
          <el-input v-model="currentAchievement.name" />
        </el-form-item>
        <el-form-item label="成就描述" prop="description">
          <el-input v-model="currentAchievement.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="图标URL" prop="iconUrl">
          <div class="avatar-upload-container">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <img v-if="currentAchievement.iconUrl" :src="currentAchievement.iconUrl" class="avatar-preview" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div v-if="currentAchievement.iconUrl" class="uploaded-image-url">{{ currentAchievement.iconUrl }}</div>
          </div>
        </el-form-item>
        <el-form-item label="成就类别" prop="category">
          <el-select v-model="currentAchievement.category" placeholder="请选择类别" style="width: 100%">
            <el-option label="签到" value="签到" />
            <el-option label="练习" value="练习" />
            <el-option label="积分" value="积分" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="条件类型" prop="conditionType">
          <el-select v-model="currentAchievement.conditionType" placeholder="请选择条件类型" style="width: 100%">
            <el-option label="首次签到" value="FIRST_CHECKIN" />
            <el-option label="连续签到" value="CONSECUTIVE_CHECKIN" />
            <el-option label="累计签到" value="ACCUMULATED_CHECKIN" />
            <el-option label="练习次数" value="PRACTICE_COUNT" />
            <el-option label="积分数量" value="POINTS_COUNT" />
          </el-select>
        </el-form-item>
        <el-form-item label="条件值" prop="conditionValue">
          <el-input-number v-model="currentAchievement.conditionValue" :min="1" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="积分奖励" prop="pointsReward">
          <el-input-number v-model="currentAchievement.pointsReward" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-switch v-model="currentAchievement.isActive" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="displayOrder">
          <el-input-number v-model="currentAchievement.displayOrder" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Picture as IconPicture } from '@element-plus/icons-vue'; // 导入Plus图标
import {
  getAchievements,
  addAchievement,
  updateAchievement,
  deleteAchievement,
  getAchievementById
} from '@/api/achievement';
import { uploadImage } from '@/api/upload';

// 数据状态
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);

// 搜索表单
const searchForm = reactive({
  name: '',
  category: ''
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 成就列表
const achievementList = ref([]);

// 当前编辑的成就
const currentAchievement = reactive({
  achievementId: null,
  name: '',
  description: '',
  iconUrl: '',
  category: '',
  conditionType: '',
  conditionValue: 1,
  pointsReward: 0,
  isActive: true,
  displayOrder: 0,
  fileObject: null  // 用于存储上传的文件对象
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入成就名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择成就类别', trigger: 'change' }],
  conditionType: [{ required: true, message: '请选择条件类型', trigger: 'change' }],
  conditionValue: [{ required: true, message: '请输入条件值', trigger: 'blur' }]
};

// 表单引用
const achievementForm = ref(null);

// 获取成就列表
const fetchAchievements = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name,
      category: searchForm.category
    };
    
    const response = await getAchievements(params);
    // 修复：根据后端返回的状态码判断，应该是200表示成功
    if (response.code === 200) {
      achievementList.value = response.data.list || response.data;
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取成就列表失败');
    }
  } catch (error) {
    ElMessage.error('获取成就列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchAchievements();
};

// 重置搜索
const handleReset = () => {
  searchForm.name = '';
  searchForm.category = '';
  pagination.currentPage = 1;
  fetchAchievements();
};

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  fetchAchievements();
};

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  fetchAchievements();
};

// 新增成就
const handleAdd = () => {
  dialogTitle.value = '新增成就';
  isEdit.value = false;
  dialogVisible.value = true;
  // 重置表单
  Object.assign(currentAchievement, {
    achievementId: null,
    name: '',
    description: '',
    iconUrl: '',
    category: '',
    conditionType: '',
    conditionValue: 1,
    pointsReward: 0,
    isActive: true,
    displayOrder: 0,
    fileObject: null
  });
};

// 编辑成就
const handleEdit = async (row) => {
  dialogTitle.value = '编辑成就';
  isEdit.value = true;
  dialogVisible.value = true;
  
  try {
    const response = await getAchievementById(row.achievementId);
    // 修复：根据后端返回的状态码判断，应该是200表示成功
    if (response.code === 200) {
      Object.assign(currentAchievement, response.data);
      // 保存原始图标URL，用于在没有重新上传图片时保持原图
      currentAchievement.originalIconUrl = response.data.iconUrl;
      // 初始化文件对象为空
      currentAchievement.fileObject = null;
    } else {
      ElMessage.error(response.message || '获取成就详情失败');
    }
  } catch (error) {
    ElMessage.error('获取成就详情失败：' + error.message);
  }
};

// 文件上传相关
const handleAvatarChange = (uploadFile) => {
  currentAchievement.iconUrl = URL.createObjectURL(uploadFile.raw);
  // 保存文件对象用于后续上传
  currentAchievement.fileObject = uploadFile.raw;
};

// 保存成就
const handleSave = async () => {
  achievementForm.value.validate(async (valid) => {
    if (valid) {
      try {
        // 如果有新上传的文件，则先上传文件
        let iconUrl = currentAchievement.iconUrl;
        if (currentAchievement.fileObject) {
          const uploadResponse = await uploadImage(currentAchievement.fileObject, '成就管理');
          if (uploadResponse.code === 200) {
            // 修复：使用正确的字段名 accessUrl 而不是 url
            iconUrl = uploadResponse.data.accessUrl || uploadResponse.data.url;
          } else {
            ElMessage.error('图片上传失败：' + (uploadResponse.message || '未知错误'));
            return;
          }
        } else if (isEdit.value && !currentAchievement.fileObject && currentAchievement.originalIconUrl) {
          // 如果是编辑模式且没有重新上传图片，则使用原始图标URL
          iconUrl = currentAchievement.originalIconUrl;
        }
        
        // 准备提交的数据
        const submitData = {
          ...currentAchievement,
          iconUrl: iconUrl
        };
        
        // 移除辅助字段
        delete submitData.fileObject;
        delete submitData.originalIconUrl;
        
        let response;
        if (isEdit.value) {
          // 更新成就
          response = await updateAchievement(currentAchievement.achievementId, submitData);
        } else {
          // 新增成就
          response = await addAchievement(submitData);
        }
        
        if (response.code === 200) {
          ElMessage.success(response.message || (isEdit.value ? '更新成功' : '新增成功'));
          dialogVisible.value = false;
          fetchAchievements();
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '新增失败'));
        }
      } catch (error) {
        ElMessage.error((isEdit.value ? '更新失败' : '新增失败') + '：' + error.message);
      }
    }
  });
};

// 删除成就
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除成就"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteAchievement(row.achievementId);
      // 修复：根据后端返回的状态码判断，应该是200表示成功
      if (response.code === 200) {
        ElMessage.success('删除成功');
        fetchAchievements();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败：' + error.message);
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 对话框关闭
const handleDialogClose = () => {
  achievementForm.value.resetFields();
  // 清理文件对象
  currentAchievement.fileObject = null;
  // 清理原始图标URL
  currentAchievement.originalIconUrl = undefined;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAchievements();
});
</script>

<style scoped>
.achievement-management {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.achievement-management .el-card__header {
  border-bottom: 1px solid #ebeef5;
}

.achievement-management .el-card__body {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 0 0 8px 8px;
  margin-top: 20px;
}

/* 优化图片上传样式，减小占用空间 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}

.uploaded-image-url {
  font-size: 12px;
  color: #606266;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  border-radius: 50%;
}

.image-slot .el-icon {
  font-size: 20px;
}

/* 优化表格样式，增加间距 */
.el-table {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.el-table__cell {
  padding: 12px 0;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #606266;
}

.el-table .el-table__cell {
  padding: 15px 0;
}

/* 优化分页样式 */
.pagination {
  margin-top: 30px;
  padding: 20px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 优化卡片样式 */
.main-card {
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 增加表单项间距 */
.el-form-item {
  margin-bottom: 22px;
}

/* 优化搜索表单 */
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.search-form .el-form-item__label {
  font-weight: 500;
}

/* 优化成就类别下拉框样式 */
.search-form .el-form-item:has(.el-select) {
  width: 100%;
}

.search-form .el-select {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .achievement-management {
    padding: 10px;
  }
  
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-col {
    margin-bottom: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-pagination {
    padding: 10px 0;
  }
  
  .avatar-uploader .el-upload {
    width: 60px;
    height: 60px;
  }
  
  .avatar-uploader-icon,
  .avatar-preview {
    width: 60px;
    height: 60px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header .el-button {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .el-dialog {
    width: 90% !important;
  }
  
  .el-form-item__label {
    width: 100% !important;
    text-align: left !important;
    margin-bottom: 5px;
  }
  
  .el-form-item__content {
    width: 100% !important;
  }
}
</style>